#!/bin/sh /etc/rc.common
# Copyright (C) 2008-2022 OpenWrt.org

START=99
USE_PROCD=1

PROG=/usr/bin/msd_lite

load_line() {
	f_line_num=$(cat /etc/msd_lite/msd_lite.conf | grep -n \<file\> | cut -d ':' -f 1)
	t_line_num=$(cat /etc/msd_lite/msd_lite.conf | grep -n \<threadsCountMax\> | cut -d ':' -f 1)
	p4_line_num=$(cat /etc/msd_lite/msd_lite.conf | grep -n \<address\> | head -n 1 | cut -d ':' -f 1)
	p6_line_num=$(cat /etc/msd_lite/msd_lite.conf | grep -n \<address\> | tail -n 1 | cut -d ':' -f 1)
	s_line_num=$(cat /etc/msd_lite/msd_lite.conf | grep -n \<ifName\> | cut -d ':' -f 1)
}


init_conf() {
	config_load "msd_lite"
	config_get "port" "config" "port"
	config_get "source" "config" "source"
	config_get "threads" "config" "threads"
	config_get "log_file" "config" "log_file"

	load_line
	n_f="             <file>${log_file}</file>"
	sed -i "${f_line_num}d" /etc/msd_lite/msd_lite.conf
	sed -i "${f_line_num}i\ ${n_f}" /etc/msd_lite/msd_lite.conf
	n_t="             <threadsCountMax>${threads}</threadsCountMax> <!-- 0 = auto -->"
	sed -i "${t_line_num}d" /etc/msd_lite/msd_lite.conf
	sed -i "${t_line_num}i\ ${n_t}" /etc/msd_lite/msd_lite.conf
	n_p4="                             <address>0.0.0.0:${port}</address>"
	sed -i "${p4_line_num}d" /etc/msd_lite/msd_lite.conf
	sed -i "${p4_line_num}i\ ${n_p4}" /etc/msd_lite/msd_lite.conf
	n_p6="                             <address>[::]:${port}</address>"
	sed -i "${p6_line_num}d" /etc/msd_lite/msd_lite.conf
	sed -i "${p6_line_num}i\ ${n_p6}" /etc/msd_lite/msd_lite.conf
	n_s="                             <ifName>${source}</ifName> <!-- For multicast receive. -->"
	sed -i "${s_line_num}d" /etc/msd_lite/msd_lite.conf
	sed -i "${s_line_num}i\ ${n_s}" /etc/msd_lite/msd_lite.conf
}

start_service() {
	init_conf

	config_get "enable" "config" "enable"
	logger -t msd_lite enable is ${enable}
	[ "${enable}" = 0 ] && return 1

	procd_open_instance
	procd_set_param command $PROG -c /etc/msd_lite/msd_lite.conf
	procd_set_param respawn
	procd_close_instance
}

service_triggers() { 
	procd_add_reload_trigger "msd_lite" 
}

reload_service() {
	stop
	start
}

stop_service() {
	service_stop $PROG
}

